﻿using System;
using System.Data;
using System.Data.Common;
using System.Xml.XPath;
using System.IO;
using System.Xml;
using System.Text;

namespace Songhay.Data.GenericWeb.OutputDefinitions
{
    using Songhay.Data.GenericWeb.DataTransferContracts;
    using Songhay.Data.GenericWeb.Procedures;

    /// <summary>
    /// Output procedures from the DBMS
    /// for <see cref="System.Xml.XPath.IXPathNavigable"/> types.
    /// </summary>
    public static partial class XPathNavigableOutput
    {
        /// <summary>
        /// Output Fragment data for editing scenarios.
        /// </summary>
        /// <param name="commonConnection">The common connection.</param>
        /// <param name="uniqueIdentifier">The unique identifier.</param>
        /// <returns>Returns <see cref="System.Xml.XPath.XPathDocument"/>.</returns>
        public static XPathDocument EditFragment(DbConnection commonConnection, string uniqueIdentifier)
        {
            if(uniqueIdentifier == null) throw new ArgumentNullException("uniqueIdentifier", "The unique identifer is null.");

            string fragmentInnerXml = Get.FragmentForEdit(commonConnection, uniqueIdentifier);
            string documents = List.Documents(commonConnection);
            string fragments = List.FragmentsForEdit(commonConnection);

            XPathDocument d = null;
            using(MemoryStream stream = new MemoryStream())
            {
                using(XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("ServerData");

                    writer.WriteRaw(fragmentInnerXml);

                    writer.WriteStartElement("SubSets");

                    writer.WriteRaw(documents);
                    writer.WriteRaw(fragments);

                    writer.WriteFullEndElement();

                    writer.WriteFullEndElement();
                    writer.WriteEndDocument();

                    writer.Flush();

                    stream.Position = 0;
                    d = new XPathDocument(stream);
                }
            }

            return d;
        }
    }
}
